import React, { Component } from 'react';
import QRCode from 'qrcode.react';
import './sharePoster.less'

export default class SharePoster extends Component {

  constructor(props) {
    super(props);
    this.state = {
      shareImg:''
    };
  }

  componentDidMount(){
    document.querySelector('body').classList.add('notScroll');
    document.querySelector('html').classList.add('notScroll');
    // console.log(document.querySelector('body'));
    setTimeout(() => {
      this.htmlToImg()
    }, 1000);

  }
  componentWillUnmount(){
    document.querySelector('body').classList.remove('notScroll');
    document.querySelector('html').classList.remove('notScroll');
  }

  renderHtml=()=>{
    let {shareUrl,size,bgImg,qrStyle,imageSettings} = this.props.options
    let option;
    if(imageSettings){
      option ={
        value:shareUrl,
        size,
        imageSettings:imageSettings
      }
    }else{
       option ={
        value:shareUrl,
        size,
      }
    }

    return (
      <div  className="imgBox">
        <QRCode style={qrStyle?{...qrStyle}:''} className="qr" {...option}></QRCode>
        <img  src={bgImg} alt=""/>
      </div>
    )
  }
  htmlToImg=()=>{
    let dom = document.querySelector('.imgBox');
    if(dom){
        let _this = this
        import('html2canvas').then((m)=>{
          m.default(dom).then(function (canvas) {
	          let base64ImgSrc = canvas.toDataURL("image/jpeg");//转成png会造成图片太大，加载缓慢，换成jpeg就好很多了
            _this.setState({
            shareImg:base64ImgSrc
            })
          })
        })
    }
  }
  renderPoster=(imgUrl)=>{
    let {dom} = this.props
    let defaultDom = (
      <div className="text">长按保存图片</div>
    )
    return (
      <div className="sharePoster">
        <div className="mask">
          <div className="box">
            <img src={imgUrl} alt=""/>
            {dom?dom:defaultDom}
          </div>
        </div>
      </div>
    )
  }

  render() {
    // console.log(this.props.options);
   const {shareImg} = this.state
   if(shareImg){
     return(
      this.renderPoster(shareImg)
     )
   }
   return (
     this.renderHtml()
   )
  }
}